package com.sweet.jpa.query;

import com.sweet.jpa.domain.Sort;
import com.sweet.lang.StringUtil;
import com.sweet.util.Assert;

import java.util.List;

/**
 * 查询语言工具，仿自org.springframework.data.jpa.repository.query.QueryUtils
 *
 * @author limi
 * @create 2018-03-20-14:26
 */
public final class QueryUtil {
    public static final String COUNT_QUERY_STRING = "select count(*) from %s";//查询总数
    public static final String DELETE_ALL_QUERY_STRING = "delete from %s";     //删除全部

    private QueryUtil() {
    }

    /**
     * 获取删除全部语句
     *
     * @param entityName 实体类名称
     * @return
     */
    public static String getDeleteAllQueryString(String entityName) {
        return String.format(DELETE_ALL_QUERY_STRING, entityName);
    }

    /**
     * 获取查询数量语句
     *
     * @param entityName 实体类名称
     * @return
     */
    public static String getCountQueryString(String entityName) {
        return String.format(COUNT_QUERY_STRING, entityName);
    }

    /**
     * 从查询语句中解析出count语句
     *
     * @param queryString
     * @return
     */
    public static String parseCountQueryString(String queryString) {
        // 找到起始关键字位置
        String search = "from ";
        int fromIndex = StringUtil.indexOfIgnoreCase(queryString, search);
        if (fromIndex < 0) {
            throw new RuntimeException(String.format("查询语句'%s'找不到'%s'关键字!", queryString, search));
        }

        //定义sql语句
        return String.format(COUNT_QUERY_STRING, queryString.substring(fromIndex + search.length()));
    }

    /**
     * 获取查询语句，无排序
     *
     * @param entityName
     * @return
     */
    public static String getQueryString(String entityName) {
        return "from " + entityName;
    }

    /**
     * 获取查询语句，支持排序
     *
     * @param entityName
     * @param sort
     * @return
     */
    public static String getQueryString(String entityName, Sort sort) {
        return applySorting(getQueryString(entityName), sort);
    }

    /**
     * 拼接完整的排序查询语句
     *
     * @param query 查询语句
     * @param sort  排序规则
     * @return
     */
    public static String applySorting(String query, Sort sort) {
        Assert.notBlank(query, "Query must not be null or empty or blank!");

        //获取排序规则，无规则则原样返回
        List<Sort.Order> orders = sort == null ? null : sort.getOrders();
        if (orders == null || orders.size() == 0) {
            return query;
        }

        //定义语句
        StringBuilder orderBy = null;

        //追加字段
        for (Sort.Order order : orders) {
            if (order != null) {
                if (orderBy == null) {
                    orderBy = new StringBuilder(" order by ");
                }

                orderBy.append(order.getProperty()).append(" ").append(order.getDirection()).append(",");
            }
        }

        //排序语句未生成，则原样返回
        if (orderBy == null) {
            return query;
        }

        //剔除最后一个逗号
        int symbolIndex = orderBy.lastIndexOf(",");
        if (symbolIndex > -1) {
            orderBy.deleteCharAt(orderBy.lastIndexOf(","));
        }

        return new StringBuilder(query).append(orderBy).toString();
    }
}